var express = require('express');
var router = express.Router();
var { UserModel, CartGoodsModel, OrderGoodsModel, AddressModel } = require('../db/index');

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});

// 获取购物车商品列表
router.get("/getCartGoods", async (req, res) => {
    let { checked } = req.query
    let search = {}
    if (checked) {
        search.isChecked = checked
    }
    let cartGoods = await CartGoodsModel.find(search)
    res.send({
        code: 200,
        msg: '获取成功',
        cartGoods
    })
})

// 更改购物车选中状态
router.put('/updateCartChecked', async (req, res) => {
    const { _id } = req.body
    const cartItem = await CartGoodsModel.findById(_id);
    // 更新选中状态（取反）
    cartItem.isChecked = !cartItem.isChecked;
    await cartItem.save()
    res.send({
        code: 200,
        msg: '更新成功',
    });
})

// 批量更改购物车选中状态
router.put("/updateCartCheckedBatch", async (req, res) => {
    const { isChecked } = req.body;
    // 更新所有商品的选中状态
    await CartGoodsModel.updateMany({}, { isChecked });
    res.send({
        code: 200,
        msg: '更新成功',
    });
});

// 修改购物车商品数量
router.put('/updateCartNum', async (req, res) => {
    const { _id, num } = req.body;
    const cartItem = await CartGoodsModel.findById(_id);
    if (num === 1) {
        cartItem.goodsNum++;
        await cartItem.save();
    } else {
        cartItem.goodsNum--;
        await cartItem.save();
    }
    res.send({
        code: 200,
        msg: '更新成功',
    });
})



const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;

// 配置支付宝沙箱环境
const alipaySdk = new AlipaySdk({
    appId: '9021000144679298',
    privateKey: 'MIIEowIBAAKCAQEAwxeY/Oi8HlEPFpOcdxpAEjKuWG6JYB/v8bX7vkF01orPad3mIwzggK/Fl2XDBfkPyxp6sSW7Na74gdq91/7NogMgqJm0X6fS8uIViwVTGIRPjrnuqYibVtc6vcivV6V0FEldPPcN1ata6wfvafp7sjOaer9hpW39E2ffzwirXivlVHQxz/+Pgsidf3xHMwmrv82bSCNcjhOxi/ytf9+5ok1W19NtOoNZ7x191e5d82q4HN29U/aQd518xuE1kyurxU9sA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2GbYBOqdYWebH3bVzf5qFpEoUWzJOGe7fLXglJ8Pkp2L41niZQKBgH4jOfAQXdnyVUYX69FoVMHLtkR5xaP1mBlIZFb5ag3+7AtN+f1rB5EQYJ1lHKWjoUEz+Z6vWb2rJIML5HXB5XWP4OvXoe/9IK+Heg3Ub2xRJRp0on4oUYpp68Ec+KKk1f7F0SfpPuzF8/z6sZgN8Rd3fEznqfcOjVLSlPGmekOh',
    gateway: 'https://openapi-sandbox.dl.alipaydev.com/gateway.do', // 沙箱环境网关
    alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgA+eZ11aiLWyUvdnFmLE9lQnR92Q7bLUw/WZHhtyW6yb5RA1i4Lnh0UkMCMEwYEpYhbEOnIsTyuQwjGyJP5M5AHUIRGmk5l/uC5CePCqRhPvwy4QE0iseZFDI2np7i1DIhC0VQKFdNsgNbr82lIiVde+acl3XVIH2w7rKBNyXO0P1qPED1PC9qDZWmj771QJV5BLuHsAkqQ21RVQZlkARtvIsi15iCCoEWQc3nDIZvOjchFshvH8+/7Ld1DB2gL8MmN+sspk6pDTb6PS86zLkLgsoG3+iFOHJTwlrVRUTKo6iXeCRCJcet/DhDjf0QLj2PskvNfPoi7LYHK6xaDinwIDAQAB',
});

// 创建订单并获取支付链接
router.post('/createOrder', async (req, res) => {
    const { address } = req.body; // 获取前端传来的地址信息
    
    // 生成订单号
    const orderId = 'ORDER_' + Date.now();
    // 获取选中的商品
    const cartGoods = await CartGoodsModel.find({ isChecked: true });
    // 计算总价（8折后的价格）
    const totalAmount = cartGoods.reduce((sum, item) => {
        return sum + (item.goodsPrice * item.goodsNum);
    }, 0) * 0.8;

    try {
        // 将选中的购物车商品添加到订单商品集合，同时添加地址信息
        const orderGoods = cartGoods.map(item => ({
            shopName: item.shopName,
            goodsName: item.goodsName,
            goodsDes: item.goodsDes,
            goodsImgsrc: item.goodsImgsrc,
            goodsPrice: item.goodsPrice,
            goodsNum: item.goodsNum,
            orderTime: new Date(), // 添加下单时间
            // 添加收货地址信息
            address: {
                username: address.username,
                phone: address.phone,
                address: address.address,
                dAddress: address.dAddress
            }
        }));
        
        // 批量创建订单商品记录
        await OrderGoodsModel.insertMany(orderGoods);
        
        // 删除已选中的购物车商品
        await CartGoodsModel.deleteMany({ isChecked: true });

        const formData = new AlipayFormData();
        formData.setMethod('get');
        formData.addField('returnUrl', 'http://localhost:10086/user/pages/cart/index');
        formData.addField('bizContent', {
            outTradeNo: orderId,
            totalAmount: totalAmount.toFixed(2),
            subject: '商品购买',
            productCode: 'QUICK_WAP_WAY'
        });

        const result = await alipaySdk.exec('alipay.trade.wap.pay', {}, { formData });

        if (result) {
            res.send({
                code: 200,
                msg: '订单创建成功',
                data: {
                    payUrl: result
                }
            });
        }
    } catch (error) {
        console.error('创建订单失败:', error);
        res.send({
            code: 500,
            msg: '创建订单失败',
            error: error.message
        });
    }
});

// 获取收货地址
router.get('/getAddress', async (req, res) => {
    let address = await AddressModel.find()
    res.send({
        code: 200,
        msg: '获取成功',
        address
    })
})

module.exports = router;
